package tech.aistar.controller.registerAndLogin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import tech.aistar.entity.User.*;
import tech.aistar.entity.authordis.UserTable;
import tech.aistar.exception.LogginException;

import tech.aistar.service.registerAndLogin.IUserRegisterService;
import tech.aistar.util.Random_util;


import java.util.HashMap;
import java.util.List;
import java.util.Map;


/*
  账号注册
 */

@Controller
@RequestMapping("/user")
public class Registered {

    @Autowired
    private IUserRegisterService userRegisterService;

    @Autowired
    JavaMailSenderImpl mailSender;

    //转发页面
    @RequestMapping("/loginview")
    public String retunLonginview(){
        return "register/bindphone_register";
    }

    //   Ajax 验证手机号码
    @GetMapping("/checkphone")
    public @ResponseBody
    UserResult checkPhone (UserTable userTable) throws LogginException {

        UserTable u = userRegisterService.findByPhone(userTable.getPhone());
        if(null == u) {

            return  new UserResult(CodeStatus.OK,true,"手机号可用",null);
        }else{
            return  new UserResult(CodeStatus.ERROR,false,"手机号不可用",null);
        }
    }

    //给用户发送邮件
    @PostMapping("/sendcode")
    public void code(Register user){


        SimpleMailMessage message = new SimpleMailMessage();
        StringBuffer ver_code = Random_util.getRandom();

        userRegisterService.insert(user.getPhone(),user.getPassword(),user.getEmail(), String.valueOf(ver_code));
        message.setSubject("Uyou网-验证邮件");
        message.setText("本邮件为注册Uyou网的验证码:"+String.valueOf(ver_code));
        message.setTo(user.getEmail());
        message.setFrom("2505617950@qq.com");

        mailSender.send(message);

    }

    //失去焦点后检测验证码
    @GetMapping("/checkcode")
    public @ResponseBody
    UserResult checkCode(Register user){
        Register u = userRegisterService.findByCode(user.getVerCode(),user.getPhone());
        if(null == u) {

            return  new UserResult(CodeStatus.ERROR,false,"验证码错误",null);
        }else{
            return  new UserResult(CodeStatus.OK,true,"",null);
        }
    }

    //将用户插入用户表和游记表
    @PostMapping("/insertuser")
    public void Insert(UserTable user){
        String username = "用户"+user.getPhone();
        userRegisterService.insertuser(username,user.getPhone(),user.getPassword());
        Integer user_id = userRegisterService.findId(user.getPhone());
        userRegisterService.insertNotes(user_id);

    }

    //@Validated entity.User user 是将自己定义的User的规则可以使用
    // BindingResult是用来将实体类中自定义的错误返回 两个必须同时使用
    @PostMapping("/returnlogin")
    public String register(@Validated(value = {ValidGroup1.class}) Register user, BindingResult bindingResult, Model model){
        System.out.println("user:"+user);

        List<FieldError> errorList = bindingResult.getFieldErrors();

        //定义一个Map用来封装有可能出现问题的字段和字段错误信息
        Map<String,String> errorMaps = new HashMap<>();

        if(null!=errorList && errorList.size()>0){
            for(FieldError fieldError:errorList){
                //将字段和字段的错误信息回显到页面
                System.out.println(fieldError.getField()+":"+fieldError.getDefaultMessage());
                errorMaps.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            model.addAttribute("errorMaps",errorMaps);
            return "user/loginview";
        }
        //注册成功之后跳转到登录界面
        return "redirect:/userlogin/login";
    }

}
